package usercollect

import (
	"context"
	"time"

	"mall/common/globalkey"
	"mall/common/resultx"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/internal/utils/errorhandler"
	"mall/service/forum/rpc/types/forum"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserCollectLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserCollectLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserCollectLogic {
	return &CreateUserCollectLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateUserCollectLogic) CreateUserCollect(in *forum.UserCollectInfo) (*forum.BaseIDResp, error) {
	if in.UserId == nil || *in.UserId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_USER_ID_INVALID, "")
	}

	if in.ObjectId == nil || *in.ObjectId == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_CONTENT_ID_INVALID, "")
	}

	if in.ObjectType == nil || *in.ObjectType == 0 {
		return nil, resultx.StatusError(resultx.FORUM_REACTION_TYPE_INVALID, "")
	}

	filterMap := make(map[string]map[string][]any)
	filterMap[model.ForumUserCollectColumns.UserID] = map[string][]any{
		"equalTo": {*in.UserId},
	}
	filterMap[model.ForumUserCollectColumns.ObjectID] = map[string][]any{
		"equalTo": {*in.ObjectId},
	}
	filterMap[model.ForumUserCollectColumns.ObjectType] = map[string][]any{
		"equalTo": {*in.ObjectType},
	}
	if in.PlatformId != nil && *in.PlatformId > 0 {
		filterMap[model.ForumUserCollectColumns.PlatformID] = map[string][]any{
			"equalTo": {*in.PlatformId},
		}
	}
	filterMap[model.ForumUserCollectColumns.Status] = map[string][]any{
		"equalTo": {globalkey.StatusEnabled},
	}
	list, _, err := l.svcCtx.UserCollect.GetList(l.ctx, model.M{
		"pageSize": uint64(1),
		"orderBy":  model.ForumUserCollectColumns.CollectID + " DESC",
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if len(list) > 0 {
		return &forum.BaseIDResp{
			Id: list[0].CollectID,
		}, nil
	}

	now := time.Now()
	collect := &model.ForumUserCollect{
		UserID:     *in.UserId,
		ObjectID:   *in.ObjectId,
		ObjectType: uint16(*in.ObjectType),
		CreatedAt:  now,
		UpdatedAt:  now,
	}

	if in.PlatformId != nil && *in.PlatformId > 0 {
		collect.PlatformID = uint(*in.PlatformId)
	}
	if in.Status != nil {
		collect.Status = uint8(*in.Status)
	} else {
		collect.Status = uint8(globalkey.StatusEnabled)
	}

	err = l.svcCtx.UserCollect.Insert(l.ctx, nil, collect)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &forum.BaseIDResp{
		Id: collect.CollectID,
	}, nil
}
